import Vue from "vue";
import VueRouter from "vue-router";
import { Message } from "element-ui";
import asyncRoutes from "@/router/asyncRoutes";

Vue.use(VueRouter);

export const constantRoutes = [
  {
    name: "login",
    path: "/login",
    component: () => import("@/views/Login"),
  }
];

const router = new VueRouter({
  routes: [...constantRoutes,  ...asyncRoutes],
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("BOOK_M_TOKEN");
  const userinfo = localStorage.getItem("USERINFO");
  console.log(to);
  if (to.path === "/login") {
    next();
  } else {
    if (token && userinfo) {
      next();
    } else {
      Message({
        type: "error",
        message: "请先登录",
      });
      next({
        path: "/login",
        query: {redirect: decodeURIComponent(to.fullPath)}
      });
    }
  }
});

export default router;
